import pygame
from puzzle import new_puzzle, Puzzle
from game_state import GameState
from data_manager import DataManager
from io_handler import PyGameInputHandler, PyGameOutputHandler
from user_preference import new_user_preference, UserPreference
from menu import new_main_menu

# Initialize PyGame
pygame.init()

# Set up the drawing window
info = pygame.display.Info()
screen_width = info.current_w
screen_height = info.current_h
GAME_WIDTH=480
GAME_HEIGHT=320
GAME_ASPECT = GAME_WIDTH / GAME_HEIGHT
screen_aspect = screen_width / screen_height
FONT_PT = 20
FONT_HEIGHT = 15
FONT_WIDTH = 17
PUZZLE_WRAP_WIDTH = 24
WRAP_WIDTH = 32
WRAP_HEIGHT = 4
MENU_HEIGHT = 8

if screen_aspect > GAME_ASPECT:
    # Pillarbox (black bars on the sides)
    new_width = int(screen_height * GAME_ASPECT)
    new_height = screen_height
    x_offset = (screen_width - new_width) // 2
    y_offset = 0
else:
    # Letterbox (black bars on top/bottom)
    new_width = screen_width
    new_height = int(screen_width / GAME_ASPECT)
    x_offset = 0
    y_offset = (screen_height - new_height) // 2

screen = pygame.display.set_mode([screen_width, screen_height], pygame.FULLSCREEN)
pygame.display.set_caption("PyCryptogram")

# Load a Monospace Font
pygame.font.init()
font_path = "data/LiberationMono-Regular.ttf"
font = pygame.font.Font(font_path, FONT_PT)

data_manager = DataManager()

saved_game_data = data_manager.try_load_game()

if 'game' in saved_game_data:
    user_preferences = UserPreference(saved_game_data['user_preferences']['visual_theme'], saved_game_data['user_preferences']['quote_db'])
else:
    user_preferences = new_user_preference()

game_state = GameState(data_manager, user_preferences, { 'wrap_height': WRAP_HEIGHT, 'puzzle_wrap_width': PUZZLE_WRAP_WIDTH })
game_state.open_main_menu()

screen_info = { 'game_width': GAME_WIDTH, 'game_height': GAME_HEIGHT, 'new_width': new_width, 'new_height': new_height, 'x_offset': x_offset, 'y_offset': y_offset }
font_info = { 'font': font, 'font_height': FONT_HEIGHT, 'font_width': FONT_WIDTH, 'wrap_width': WRAP_WIDTH, 'wrap_height': WRAP_HEIGHT, 'menu_height': MENU_HEIGHT }

input_handler = PyGameInputHandler()
output_handler = PyGameOutputHandler(screen, font_info, screen_info)

# Game Loop
while game_state.screen != 'exit_to_os':
    output_handler.render(game_state)
    input_handler.process_input(game_state)
    if game_state.screen == 'exit_to_os':
        print("Goodbye!")

pygame.quit()
